package com.Rsoft.goodWebsocketMan.Thread;

import com.Rsoft.goodWebsocketMan.domain.WebSocketRq;
import com.Rsoft.goodWebsocketMan.factory.ClientFactory;
import com.Rsoft.goodWebsocketMan.ui.form.func.WebSocketForm;
import lombok.Data;
import lombok.SneakyThrows;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;

@Data
public class WebSocketThread extends Thread {
    public volatile boolean flag = true;
    private WebSocketRq webSocketRq;
    private volatile WebSocketSession webSocketSession;

    public WebSocketThread(WebSocketRq webSocketRq) {
        this.webSocketRq = webSocketRq;
    }

    public void sendText(String msg) throws IOException {
        webSocketSession.sendMessage(new TextMessage(msg));
    }

    @SneakyThrows
    @Override
    public void run() {
        try {
            webSocketSession = ClientFactory.getClientSession(webSocketRq.getUrl(), webSocketRq.getHeaders());
            if (null == webSocketSession) {
                WebSocketForm.getInstance().getTips().setText("连接失败！");
                flag = false;
            }
        } catch (Exception e) {
            flag = false;
            WebSocketForm.getInstance().getTips().setText("连接失败！");
            e.printStackTrace();
        }
        while (webSocketSession.isOpen() && flag) {
            Thread.sleep(1000);
        }
        flag = false;
        WebSocketForm.getInstance().getTips().setText("连接已断开！");
        WebSocketForm.getInstance().getToConnectBt().setEnabled(true);
        webSocketSession.close();
    }
}
